using System;
using System.Linq;
using System.Windows.Forms;
using Comteck.Dto.Orders;
using Comteck.Ktt.Services.Orders;
using Comteck.Linq;
using Comteck.Localization;
using Comteck.Winforms;
using Comteck.Winforms.Forms;
using DevExpress.XtraBars;
using ExpressMapper.Extensions;
using Microsoft.Extensions.DependencyInjection;

namespace Comteck.Ktt.WinUI.Orders {
  /// <summary>
  /// 自提点标签管理
  /// </summary>
  public partial class FrmSelfOrgTagAdmin : FrmBase {
    private readonly ISelfOrgTagService selfOrgTagService;
    private CKObservableCollection<SelfOrgTagDto> mainDataList;

    public FrmSelfOrgTagAdmin(ISelfOrgTagService selfOrgTagService) {
      this.selfOrgTagService = selfOrgTagService;
      InitializeComponent();
    }

    private void FrmSelfOrgTagAdmin_Load(object sender, EventArgs e) {
      if (this.DesignMode) {
        return;
      }

      gcMain.DataSource = mainDataList = new CKObservableCollection<SelfOrgTagDto>(this);
      colCreateTime.FormatDate();
    }

    private async void btnSearch_ItemClick(object sender, ItemClickEventArgs e) {
      // search
      ajaxLoad.Show();
      var result = await selfOrgTagService.GetAllAsync();
      ajaxLoad.Hide();

      result.ToList().MapTo(mainDataList, x => x.Id, x => x.Id);
    }

    private void btnAdd_ItemClick(object sender, ItemClickEventArgs e) {
      var form = SysGlobal.ServiceProvider.GetRequiredService<FrmSelfOrgTagAction>();
      form.AddOrUpdateAction = (entity) => gvMain.BindAfterInsert<SelfOrgTagDto>(entity);
      form.Owner = this;
      form.ShowDialog();

    }

    private void btnEdit_ItemClick(object sender, ItemClickEventArgs e) {
      if (!(gvMain.GetFocusedRow() is SelfOrgTagDto model)) {
        return;
      }

      var form = SysGlobal.ServiceProvider.GetRequiredService<FrmSelfOrgTagAction>();
      form.EntityId = model.Id;
      form.AddOrUpdateAction = (entity) => gvMain.BindAfterUpdate(model, entity);
      form.Owner = this;
      form.ShowDialog();

    }

    private async void btnDelete_ItemClick(object sender, ItemClickEventArgs e) {
      if (!(gvMain.GetFocusedRow() is SelfOrgTagDto model)) {
        return;
      }

      var dialog = this.ShowMsg(BaseResources.Delete_Selected_Confirm, "提示", MessageBoxButtons.YesNo,
        MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
      if (dialog == DialogResult.No) {
        return;
      }

      ajaxLoad.Show();
      var result = await selfOrgTagService.DeleteAsync(model.Id);
      ajaxLoad.Hide();

      if (result.Code == 1) {
        mainDataList.Remove(model);
        this.ShowMsg(BaseResources.Delete_Success);
      } else {
        this.ShowMsg(BaseResources.Delete_Failed_Reason, result.Message);
      }
    }

    private void btnExport_ItemClick(object sender, ItemClickEventArgs e) {
      gvMain.ExportDialog();
    }

    private void btnClose_ItemClick(object sender, ItemClickEventArgs e) {
      this.Close();
    }
  }
}
